package com.lzm.controller;

import com.lzm.pojo.User;
import com.lzm.service.loginService;
import com.lzm.utils.Message;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


@ResponseBody
@Controller
public class loginController extends HttpServlet {

    @Resource
    private loginService loginService;
    @RequestMapping(value = "login",method = RequestMethod.POST)
    @ResponseBody
    public Message login(HttpServletRequest request, HttpServletResponse response, User user) throws IOException, ServletException {
        String verify = request.getParameter("verify");
        System.out.println(verify);
        boolean login = loginService.login(user.getUser_loginName(), user.getUser_passWord());
        Message msg = null;
        if (login){
            HttpSession session = request.getSession();
            String rand = (String) session.getAttribute("rand");
            if(verify.equals(rand)){
                msg = new Message(200,"登录成功");
                session.setAttribute("userName",user.getUser_loginName());
            }else {
                msg = new Message(500,"验证码不正确！");
            }
        }else {
            msg = new Message(500,"输入的用户名密码有误！");
        }

        return msg;

    }

    @RequestMapping("codeImage.action")
    public void createImage(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {
        loginService.service(request,response);
        HttpSession session = request.getSession();
        String rand = (String) session.getAttribute("rand");
        System.out.println("rand:"+rand);
    }

    @RequestMapping("name")
    public Message getName(HttpSession session){
        String loginName = (String) session.getAttribute("userName");
        Message msg = null;
        if(loginName== null || loginName.equals("")){
            msg = new Message(400,"非法登录！");
        }else {
            List<User> admins = loginService.queryByName(loginName);
            if (admins.size()>0){
                for (User admin : admins) {
                    msg = new Message(200,admin.getUser_trueName());
                }
            }else {
                msg = new Message(500);
            }
        }

        return  msg;
    }
    @RequestMapping("loginOut")
    public Message loginOut(HttpSession session){
        //清除session
        session.invalidate();
        Message msg = new Message(200,"退出成功！");
        return msg;
    }

}
